<template>
    <div class="common-layout">
        <el-container>
            <el-header>
                <!--条件查询-->
                <el-form :inline="true" :model="chaForm" class="demo-form-inline">  
                    <el-form-item label="签约日期">
                             <el-date-picker
                    v-model="chaForm.CreateStartTime"
                    type="date"
                    placeholder="年/月/日"
                    :size="size"
                />  ~  
                <el-date-picker
                    v-model="chaForm.CreateEndTime"
                    type="date"
                    placeholder="年/月/日"
                    :size="size"
                />
                    </el-form-item>&nbsp;&nbsp;
                <el-form-item label="签约团队">
                         <el-select v-model="chaForm.Team" placeholder="请选择团队" style="width: 150px;">
                            <el-option value="0">请选择</el-option>
                            <el-option v-for="team in teamData" :key="team.teamID"
                            :label="team.teamName" :value="team.teamID"
                            ></el-option>
                         </el-select>
                    </el-form-item>&nbsp;&nbsp;
                    <el-form-item label="姓名">
                        <el-input v-model="chaForm.ResidentFiles_Name" placeholder="请输入姓名"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="getSignData()">查询</el-button>
                    </el-form-item>
                </el-form>
            </el-header>
            <el-main>
                <el-button style="background-color: yellowgreen;"  @click="dialogFormVisible = true">+ 签约</el-button>&nbsp;
                 <el-table :data="tableData" style="width:100%">
                    <el-table-column property="ncdSign_Id" label="编号" width="110"></el-table-column>
                    <el-table-column property="residentFiles_Name" label="名字" width="110"></el-table-column>
                     <el-table-column property="sex" label="性别" width="110"></el-table-column>
                    <el-table-column property="age" label="年龄" width="110"></el-table-column>
                     <el-table-column property="phone" label="联系电话" width="130"></el-table-column>
                    <el-table-column property="idCard" label="身份证号" width="120"></el-table-column>
                     <el-table-column label="签约周期" width="310">
                         <template v-slot="scoped">
                            <el-tag effect="dark round">
                                {{scoped.row.sign_StartTime}} ~ {{scoped.row.sign_EndTime}}
                            </el-tag>
                         </template>
                     </el-table-column>
                    <el-table-column property="createTime" label="签约日期" width="130"></el-table-column>
                    <el-table-column property="teamName" label="签约团队" width="110"></el-table-column>
                    
                 </el-table>
                  <!--分页-->
    <table style="margin: 15px auto;">
    <tbody>
        <tr>
            <!--总页数-->
            <td>
                <el-pagination
      v-model:current-page="page.pageIndex"
      v-model:page-size="page.pageSize"
      :page-sizes="[2, 4, 6, 8]"
      :background="true"
      layout=" total,slot,sizes"    
      :total="page.totalCount" prev-text="上一页" next-text="下一页"
    >
<span>每页{{ page.pageSize }}条,共{{ page.pageIndex }}/{{ page.totalPage }}行</span>
                </el-pagination>
            </td>
            <!--首页-->
            <td>
                <el-pagination
      v-model:current-page="page.pageIndex"
      v-model:page-size="page.pageSize"
      :page-sizes="[2, 4, 6, 8]"
      :background="true"
      layout=" solt,prev,pager,next"    
      :total="page.totalCount" prev-text="上一页" next-text="下一页">
      <button class="btn-prev" :disabled="page.pageIndex==1" @click="page.pageIndex=1">首页</button>
            </el-pagination>
            </td>
            <!--尾页-->
            <td>
                <el-pagination
      v-model:current-page="page.pageIndex"
      v-model:page-size="page.pageSize"
      :page-sizes="[2, 4, 6, 8]"
      :background="true"
      layout=" solt,jumper"    
      :total="page.totalCount" prev-text="上一页" next-text="下一页">
      <button class="btn-next" :disabled="page.pageIndex==page.totalPage" @click="page.pageIndex=page.totalPage">尾页</button>
            </el-pagination>
            </td>
        </tr>
    </tbody>
  </table>
           </el-main>
        </el-container>
    </div>
    <!--弹出框添加-->
    <!--添加患者签约信息-->
    <el-dialog v-model="dialogFormVisible" title="慢病签约" width="45%" @close="handleDialogClose">
        <!-- 查询患者 -->
         <el-row :gutter="50">
                  <el-col :span="24">
                    <el-form-item label="查询患者">
                      <el-input v-model="chaPatient.ResidentFiles_Name" style="width: 13vw;
    height: 3vh;" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <p>
                  <span>{{patientData.residentFiles_Name}}</span>&nbsp;&nbsp;&nbsp;<span>{{patientData.sex}}</span>&nbsp;<span>{{patientData.age}}岁</span>&nbsp;&nbsp;
                  <span>出生日期：{{patientData.birthday}}</span>&nbsp;&nbsp;&nbsp;<span>身份证号：{{patientData.idCard}}</span>

                </p>
                <!--签约信息-->
              <el-form :model="ncdSignForm" >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="签约团队">
                         <el-select v-model="ncdSignForm.Team" placeholder="请选择团队" style="width: 150px;">
                            <el-option v-for="team in teamData" :key="team.teamID"
                            :label="team.teamName" :value="team.teamID"
                            ></el-option>
                         </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                        <el-form-item label="主管医生">
                         <el-select v-model="ncdSignForm.doctor" placeholder="请选择医生" style="width: 150px;">
                            <el-option v-for="doctor in doctorData" :key="doctor.teamID"
                            :label="doctor.doctorName" :value="doctor.doctorName"
                            ></el-option>
                         </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-form-item label="签约周期">
                       <el-date-picker v-model="ncdSignForm.sign_StartTime" type="date" placeholder="选择开始日期" style="width: 13vw;
    height: 3vh;"/>
                    </el-form-item>~ 
                    <el-date-picker v-model="ncdSignForm.sign_EndTime" type="date" placeholder="选择结束日期" style="width: 13vw;
    height: 3vh;"/>
                </el-row>
                <el-form-item label="管理慢病">
                   <el-checkbox-group v-model="ncdSignForm.manageNCD">
                      <el-checkbox value="高血压" name="manageNCD">
                        高血压
                      </el-checkbox>
                      <el-checkbox value="高血糖" name="manageNCD">
                        高血糖
                      </el-checkbox>
                      <el-checkbox value="高血脂" name="manageNCD">
                        高血脂
                      </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-row :gutter="20">
                    <el-form-item label="管理级别">
                       <el-select v-model="ncdSignForm.manageLevel" placeholder="请选择" style="width: 150px;">
                            <el-option value="一级">一级</el-option>
                            <el-option value="二级">二级</el-option>
                            <el-option value="三级">三级</el-option>
                         </el-select>
                    </el-form-item>
                </el-row>
              </el-form>
              <p>服务包</p>
               <el-table :data="packData" style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column property="servicesPack_Name" label="服务名称" width="120" />
                    <el-table-column property="cost" label="费用" width="240" show-overflow-tooltip/>
                    <el-table-column label="操作" width="310">
                         <template #default>
                            <el-tag effect="dark round">
                                服务项目
                            </el-tag>
                         </template>
                     </el-table-column>
                </el-table><br />
                <p>绑定设备 <a style="color:orange;cursor:pointer;" @click="OpenDeviceBind">+ 绑定</a></p>
                      <el-table :data="deviceData" style="width:100%">
                    <el-table-column property="device_Name" label="设备名称" width="110"></el-table-column>
                    <el-table-column property="device_SN" label="设备SN号" width="110"></el-table-column>
                     <el-table-column property="bind_Time" label="绑定时间" width="110"></el-table-column>
                    <el-table-column  label="状态" width="110">
                        <template #default>在绑</template>
                    </el-table-column>
                     <el-table-column label="操作" width="310">
                         <template v-slot="scoped">
                          <a style="color:blue;cursor:pointer;" @click="unbindDevice(scoped.row.id)">解绑</a>
                         </template>
                     </el-table-column>
                 </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addSign">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogDeviceVisible" title="设备绑定" width="35%">
      <el-button type="primary" @click="addPatientBindDevice">绑定</el-button>
        <el-table :data="deviceAllData" style="width:100%" @selection-change="handDeviceSelection">
                    <el-table-column type="selection" width="55" />
                    <el-table-column property="device_Name" label="设备名称" width="110"></el-table-column>
                    <el-table-column property="device_Code" label="设备编码" width="110"></el-table-column>
                    <el-table-column property="device_SN" label="设备SN号" width="110"></el-table-column>
                    <el-table-column property="device_Brand" label="品牌" width="110"></el-table-column>
                    <el-table-column property="device_Model" label="型号" width="110"></el-table-column>

                   
                 </el-table>
    </el-dialog>
</template>
<script setup lang="ts">
import {  reactive, ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useCounterStore } from '@/stores/counter'
import axios from 'axios'
const apiUrl = import.meta.env.VITE_APP_API_URL;
import { ElMessage, ElMessageBox } from 'element-plus'
    const store = useCounterStore()
    const router = useRouter()
    //弹窗显示状态
    const dialogFormVisible = ref(false);
    const dialogDeviceVisible = ref(false);

    const chaForm = reactive({
      CreateStartTime: "",
      CreateEndTime: "",
      ResidentFiles_Name: "",
      ResidentFiles_Id: 0,
      Team: null,
      Doctor_Name: '',
      PageIndex: 1,
      PageSize: 15
    })

    const page = reactive({
      pageIndex: 1,
      pageSize: 15,
      totalCount: 0,
      totalPage: 0
    })

    const tableData = ref([])
    const teamData = ref([])

    const getTeamData = async () => {
      try {
        const res = await axios.get(apiUrl+'/T7/Sign/GetTeamSlect')
        teamData.value = res.data.data
      } catch (error) {
        ElMessage.error('获取团队数据失败')
      }
    }
    const getDoctorData = async () => {
      try {
        const res = await axios.get(apiUrl+`/T7/Sign/GetDoctorSelect?TeamID=${ncdSignForm.Team}`)
        doctorData.value = res.data.data
      } catch (error) {
        ElMessage.error('获取医生数据失败')
      }
    }
     const getPackData = async () => {
      try {
        const res = await axios.get(apiUrl+'/T7/Sign/GetServicesPack')
        packData.value = res.data.data
      } catch (error) {
        ElMessage.error('获取服务包数据失败')
      }
    }
    const getSignData = async () => {
      try {
        const res = await axios.get(apiUrl+"/T7/Sign/GetResidentFilesList", {
          params: {
            PageIndex: page.pageIndex,
            PageSize: page.pageSize,
            CreateStartTime: chaForm.CreateStartTime,
            CreateEndTime: chaForm.CreateEndTime,
            ResidentFiles_Name: chaForm.ResidentFiles_Name,
            ResidentFiles_Id: chaForm.ResidentFiles_Id,
            Team: chaForm.Team,
            Doctor_Name: chaForm.Doctor_Name,
          }
        })
        tableData.value = res.data.list
        page.totalCount = res.data.totalCount
        page.totalPage = res.data.totalPage
      } catch (error) {
        ElMessage.error('获取签约数据失败')
      }
    }
    const getPatientData = async () => {
      try {
        const res = await axios.get(apiUrl+'/T7/ResidentFiles/GetResidentFilesSelect}',{
          params: {
            ResidentFiles_Name: chaPatient.ResidentFiles_Name
          }
        })
        patientData.age = res.data.data.age;
        patientData.idCard = res.data.data.idCard;
        patientData.sex = res.data.data.sex;
        patientData.birthday = res.data.data.birthday;
        patientData.residentFiles_Id = res.data.data.residentFiles_Id;
        patientData.residentFiles_Name = res.data.data.residentFiles_Name;

      } catch (error) {
        ElMessage.error('获取患者数据失败')
      } 
    }
     const chaPatient = reactive({ResidentFiles_Name:''})
     const patientData = reactive({residentFiles_Id:0,residentFiles_Name:'',sex:'',age:0,idCard:'',birthday:''})
     const packData = ref([])
     const doctorData = ref([])
     const deviceData = ref([])
     const deviceAllData = ref([])
     const ncdSignForm = reactive({
      ncdSign_Id:0,
      patient_Id:0,
      Team: null,
      doctor: '',
      sign_Status:1,
      sign_StartTime: '',
      sign_EndTime: '',
      manageNCD: [],
      manageLevel: '',
      servicePack: '',
      proof:'',
      createUser:'',
      createTime:'',
      updateUser:'',
      updateTime:''
    })
    const selectedServices = ref<string[]>([]);

    // 监听选中项变化
    const handleSelectionChange = (selection: any[]) => {
      const names = selection.map(item => item.servicesPack_Name);
      selectedServices.value = names;
      ncdSignForm.servicePack = names.join(','); // 拼接为字符串
    };
    const selectedDevices = ref<any[]>([]);
   const handDeviceSelection = (selection: any[]) => {
      selectedDevices.value = selection;
    };
    const handleDialogClose = () => {
      //弹出框消失，所有数据更新
      Object.assign(chaPatient,{ResidentFiles_Name:''})
      Object.assign(patientData,{residentFiles_Id:0,residentFiles_Name:'',sex:'',age:0,idCard:'',birthday:''});
      Object.assign(ncdSignForm,{
        ncdSign_Id:0,
        patient_Id:0,
        Team: null,
        doctor: '',
        sign_Status:1,
        sign_StartTime: '',
        sign_EndTime: '',
        manageNCD: [],
        manageLevel: '',
        servicePack: '',
        proof:'',
        createUser:'',
        createTime:'',
      })
      deviceData.value = [];
      selectedServices.value = [];
      selectedDevices.value = [];
      getPackData();
    }
    const addPatientBindDevice = async () => {
        if (selectedDevices.value.length === 0) {
          ElMessage.warning("请至少选择一个设备");
          return;
        }

        const now = new Date().toISOString();
        const currentUser = store.ccstore.userName || "admin";

        // 构造 signDeviceBinds 数组
        const signDeviceBinds = selectedDevices.value.map(device => ({
              createUser: currentUser,
              createTime: now,
              updateUser: currentUser,
              updateTime: now,
              id: 0,
              device_Id: device.id, 
              patient_Id: patientData.residentFiles_Id,
              device_Name: device.device_Name,
              device_Code: device.device_Code,
              device_Model: device.device_Model,
              device_SN: device.device_SN,
              bind_Status: 1,
              bind_Time: now
            }));

            try {
              const res = await axios.post(apiUrl+'/T8/Sign/AddSignDeviceBind', {
                signDeviceBinds
              });

              if (res.data.code === 212) {
                ElMessage.success("绑定成功");

                // 刷新设备列表
                const res2 = await axios.get(apiUrl+'/T7/Sign/GetSignDeviceBindList', {
                  params: {
                    ResidentFiles_Id: patientData.residentFiles_Id
                  }
                });
                deviceData.value = res2.data.data;

                // 关闭弹窗
                dialogDeviceVisible.value = false;
              } else {
                ElMessage.error(res.data.msg || '绑定失败');
              }
            } catch (error) {
              ElMessage.error('网络请求失败');
            }
    };
    const addSign = async () => {
        try {
          // 校验必要字段
          if (!ncdSignForm.Team || !ncdSignForm.doctor || !ncdSignForm.sign_StartTime || !ncdSignForm.sign_EndTime) {
            ElMessage.warning('请填写完整信息');
            return;
          }

          const payload = {
            patient_Id: patientData.residentFiles_Id, 
            team: ncdSignForm.Team,
            doctor: ncdSignForm.doctor,
            sign_Status: ncdSignForm.sign_Status,
            sign_StartTime: ncdSignForm.sign_StartTime,
            sign_EndTime: ncdSignForm.sign_EndTime,
            manageNCD: ncdSignForm.manageNCD.join(','), // 数组转字符串
            manageLevel: ncdSignForm.manageLevel,
            servicePack: ncdSignForm.servicePack,
            proof: 'string',
            createUser: store.ccstore.userName,
            createTime: new Date().toISOString(),
            updateUser: store.ccstore.userName,
            updateTime: new Date().toISOString()
          };

          const res = await axios.post(apiUrl+'/T8/Sign/AddNCDSign', payload);

          if (res.data.code === 212) {
            ElMessage.success('签约成功');
            dialogFormVisible.value = false;
            getSignData(); // 刷新列表
          } else {
            ElMessage.error(res.data.msg || '签约失败');
          }
        } catch (error) {
          ElMessage.error('网络请求失败');
        }
      };
      const unbindDevice = async(id)=>{
        ElMessageBox.confirm('确定要解绑吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const params = {id:id};
           var res = await axios.post(apiUrl+'/T8/Sign/DelSignDeviceBind',params)
           if (res.data.code === 204) {
            ElMessage.success('解绑成功');
            const res2 = await axios.get(apiUrl+'/T7/Sign/GetSignDeviceBindList',{
          params:{
            ResidentFiles_Id:patientData.residentFiles_Id
          }
         })
        deviceData.value = res2.data.data;
          } else {
            ElMessage.error(res.data.msg || '解绑失败');
          }

        })
      }
     
      const OpenDeviceBind = async() => {
       if(patientData.residentFiles_Id == null || patientData.residentFiles_Id == 0){
        ElMessage.warning("请先选择患者");
       }else{
         dialogDeviceVisible.value = true;
        var res = await axios.get(apiUrl+'/T7/BasicSettings/GetDeviceInfo',{
          params:{pageIndex:1,pageSize:1000}
        })
        deviceAllData.value = res.data.list;
       }

      }
    watch(page, () => {
      getSignData()
    })
    // 添加 watch 监听输入值变化
    watch(
      () => chaPatient.ResidentFiles_Name,
      async (newVal) => {
        if (newVal.trim() !== '') {
          try {
              const res = await axios.get(apiUrl+'/T7/ResidentFiles/GetResident',{
          params: {
            ResidentFiles_Name: chaPatient.ResidentFiles_Name
          }
        })
         patientData.age = res.data.data.age;
        patientData.idCard = res.data.data.idCard;
        patientData.sex = res.data.data.sex;
        patientData.birthday = res.data.data.birthday;
        patientData.residentFiles_Id = res.data.data.residentFiles_Id;
        patientData.residentFiles_Name = res.data.data.residentFiles_Name;

         const res2 = await axios.get(apiUrl+'/T7/Sign/GetSignDeviceBindList',{
          params:{
            ResidentFiles_Id:patientData.residentFiles_Id
          }
         })
        deviceData.value = res2.data.data;

          } catch (error) {
            ElMessage.error('获取信息失败');
          }
        }
      }
    );
    watch(
      () => ncdSignForm.Team,
      (newTeamId) => {
        if (newTeamId) {
          getDoctorData();
        }
      }
    );
    onMounted(() => {
      getTeamData()
      getSignData()
      getPackData()
    })


</script>
<style scoped>
    /* 全局样式规范 */
:root {
  /* 企业主色（建议使用品牌色） */
  --primary-color: #409eff;
  /* 辅助色 */
  --success-color: #67c23a;
  --warning-color: #f90;
  --danger-color: #f56c6c;
  --info-color: #909399;
  
  /* 字体规范 */
  --font-primary: "PingFang SC", "Helvetica Neue", Helvetica, Arial, sans-serif;
  --font-size-base: 14px;
  --font-size-lg: 16px;
  --font-weight-medium: 500;
  
  /* 间距规范 */
  --padding-base: 16px;
  --margin-base: 12px;
  --line-height-base: 1.5;
  
  /* 表格样式 */
  --table-row-height: 44px;
}

/* 全局基础样式 */
.common-layout {
  font-family: var(--font-primary);
  font-size: var(--font-size-base);
  line-height: var(--line-height-base);
  color: #303133;
}

.el-container {
  min-height: 100vh;
}

.el-header {
  padding: var(--padding-base);
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebedf0;
}

.el-main {
  padding: var(--padding-base 24px);
  background-color: #fff;
}

/* 表单样式优化 */
.demo-form-inline {
  display: flex;
  align-items: center;
  gap: var(--margin-base);
}

.el-form-item {
  margin-bottom: 0;
}

.el-input,
.el-select {
  height: 40px;
  border-radius: 4px;
}

/* 按钮样式规范（统一使用组件内置类型，避免内联样式） */
.el-button {
  font-size: var(--font-size-base);
  border-radius: 4px;
  padding: 0 16px;
}

.el-button.primary {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
}

.el-button.success {
  background-color: var(--success-color);
  border-color: var(--success-color);
}

.el-button.warning {
  background-color: var(--warning-color);
  border-color: var(--warning-color);
}

.el-button.danger {
  background-color: var(--danger-color);
  border-color: var(--danger-color);
}

/* 表格样式优化 */
.el-table {
  margin-top: var(--margin-base);
  border-radius: 8px;
  overflow: hidden;
}

.el-table__header-wrapper {
  background-color: #f5f7fa;
}

.el-table__row {
  height: var(--table-row-height);
}

.el-table__cell {
  padding: 0 16px;
  border-bottom: 1px solid #ebedf0;
  font-size: var(--font-size-base);
}

.el-table--striped .el-table__body tr.el-table__row--striped {
  background-color: #f9fafc;
}

/* 状态标签样式 */
.el-tag {
  font-size: var(--font-size-base);
  padding: 4px 12px;
}

/* 弹窗样式优化 */
.el-dialog {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.el-dialog__header {
  padding: var(--padding-base);
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebedf0;
}

.el-dialog__title {
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-medium);
}

.el-dialog__body {
  padding: var(--padding-base 24px);
}

.el-form-item {
  margin-bottom: 20px;
}

/* 分页样式优化 */
.el-pagination {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: flex-end; /* 建议右对齐，符合企业规范 */
}

.el-pagination__sizes {
  margin-right: var(--margin-base);
}

.el-pagination__editor {
  width: 60px;
  margin: 0 8px;
}

/* 操作按钮组样式 */
.el-table__fixed-right {
  padding-right: 16px; /* 固定列右侧间距 */
}

.table-operation {
  display: flex;
  gap: 8px;
}

/* 禁用状态样式 */
[disabled],
.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
/* 响应式优化 */
@media (max-width: 768px) {
  .el-main {
    padding: var(--padding-base);
  }
  
  .el-table {
    font-size: 13px;
  }
}
</style>